package nacos

import (
	"encoding/json"
	"enjoy-joy/common/viper"
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
)

type Nacos struct {
	Mysql struct {
		User     string `json:"user"`
		Password string `json:"password"`
		Host     string `json:"host"`
		Port     string `json:"port"`
		Database string `json:"database"`
	} `json:"mysql"`
	Redis struct {
		Addr     string `json:"addr"`
		Password string `json:"password"`
		Db       int    `json:"db"`
	} `json:"redis"`
	Grpc struct {
		Host string `json:"host"`
		Port int    `json:"port"`
	} `json:"grpc"`
	Consul struct {
		Name string `json:"name"`
		Host string `json:"host"`
		Port int    `json:"port"`
	} `json:"consul"`
	Aliyun struct {
		AccessKeyId     string `json:"AccessKeyId"`
		AccessKeySecret string `json:"AccessKeySecret"`
	} `json:"aliyun"`
	Es struct {
		Host string `json:"host"`
	} `json:"es"`
	Email struct {
		FormEmail string `json:"FormEmail"`
		Password  string `json:"Password"`
	} `json:"email"`
}

var NacosConfig Nacos

func NewNacos() {
	clientConfig := constant.ClientConfig{
		NamespaceId:         viper.Conf.Nacos.Name,
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		LogLevel:            "debug",
	}
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      viper.Conf.Nacos.Host,
			ContextPath: "/nacos",
			Port:        uint64(viper.Conf.Nacos.Port),
			Scheme:      "http",
		},
	}
	client, err := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})
	if err != nil {
		return
	}

	content, err := client.GetConfig(vo.ConfigParam{
		DataId: viper.Conf.Nacos.DataId,
		Group:  viper.Conf.Nacos.Group})
	err = json.Unmarshal([]byte(content), &NacosConfig)
	if err != nil {
		return
	}

	err = client.ListenConfig(vo.ConfigParam{
		DataId: viper.Conf.Nacos.DataId,
		Group:  viper.Conf.Nacos.Group,
		OnChange: func(namespace, group, dataId, data string) {
			fmt.Println("group:" + group + ", dataId:" + dataId + ", data:" + data)
			err = json.Unmarshal([]byte(data), &NacosConfig)
			if err != nil {
				return
			}
		},
	})
}
